﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace SG.Ling.AutoTranslator.Common
{
    public enum ArgumentType
    {
        Empty = 0,
        Option = 0x1,
        Command = 0x2,
    }

    public struct ArgumentTuple
    {
        public ArgumentType Type;
        public string Text;
    }

    public class ArgumentParser : IEnumerable<ArgumentTuple>
    {
        private readonly ArgumentTuple[] _parsed;

        public ArgumentParser(ICollection<string> args)
        {
            _parsed = new ArgumentTuple[args != null ? args.Count : 0];

            if (args == null)
                return;

            var outIndex = 0;
            foreach (var arg in args.Where(arg => arg.Length > 0))
            {
                switch (arg[0])
                {
                    case '/':
                    case '-':
                        _parsed[outIndex] = new ArgumentTuple
                                                {Type = ArgumentType.Option, Text = arg.Substring(1).ToLowerInvariant()};
                        break;

                    default:
                        _parsed[outIndex] = new ArgumentTuple {Type = ArgumentType.Command, Text = arg};
                        break;
                }

                outIndex++;
            }
        }

        public bool HasFlag(string name)
        {
            return this.Any(arg => arg.Type == ArgumentType.Option && arg.Text == name);
        }

        public IEnumerable<ArgumentTuple> Commands()
        {
            return this.Where(arg => arg.Type == ArgumentType.Command);
        }

        public IEnumerator<ArgumentTuple> GetEnumerator()
        {
            return ((IEnumerable<ArgumentTuple>) _parsed).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
